
<template>
  <div class="theme-setting">
    <div
      class="theme-setting__wrapper"
      @click="showThemeSetting"
    >
      <i class="el-icon-setting" />
      <span>主题设置</span>
    </div>
    <baseDialog
      ref="baseDialog"
      title="主题设置"
      @comfire="comfireFun"
    >
      <template slot="content">
        <el-scrollbar
          class="scrollbarCls is-horizontal--none"
        >
          <Form
            ref="Form"
            v-model="initFormData"
            :item-data="formData"
            :form-config="formConfig"
            @change="changeFun"
          />
        </el-scrollbar>
      </template>
    </baseDialog>
  </div>
</template>

<script>
import baseDialog from '@/components/baseDialog/index.vue'
import Form from '@/components/Form/index.vue'
// import axios from 'axios'
// import { theme } from '@/api/login'
export default {
  name: 'Theme',
  components: {
    baseDialog,
    Form
  },
  data () {
    return {
      visible: false,
      initFormData: {
        theme: 'theme2',
        fontColor: 'red',
        bgColor: '',
        hoverColor: ''
      },
      formData: [
        {
          props: 'theme',
          label: '主题',
          type: 'el-select-options',
          config: {
            placeholder: '请选择主题后自定义颜色不生效',
            options: [
              { label: '天空蓝', value: 'theme1' },
              { label: '深黑灰', value: 'theme2' },
              { label: '中国红', value: 'theme3' },
              { label: '自定义主题色', value: 'custom' }
            ],
            filterable: true
          }
        },
        {
          props: 'fontColor',
          label: '字体颜色',
          type: 'el-color-picker',
          show: false
        },
        {
          props: 'bgColor',
          label: '背景颜色',
          type: 'el-color-picker',
          show: false
        },
        {
          props: 'hoverColor',
          label: '移入(激活)状态',
          type: 'el-color-picker',
          show: false
        }
      ],
      formConfig: {
        labelWidth: '120px',
        labelPosition: 'left'
      }
    }
  },
  mounted () {
    window.document.body.setAttribute('data-theme', 'theme2')
    // this.update({ fontColor: 'red' })
    // this.handleStyle()
  },
  methods: {
    // 异步获取link链接的样式
    getCSSString (url) {
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4 && xhr.status === 200) {
            resolve(xhr.responseText)
          }
        }
        xhr.open('GET', url)
        xhr.send()
      })
    },
    async comfireFun () {
      // this.handleStyle(this.initFormData)
    },
    changeFun ({ prop, value }) {
      const mapKey = {
        fontColor: 'color',
        bgColor: 'background-color'
      }
      if (prop === 'theme') { // 改变主题色类型
        const targetShow = this.formData.filter(v => v.type === 'el-color-picker')
        targetShow.forEach((v) => {
          this.$set(v, 'show', value === 'custom')
        })
        window.document.body.setAttribute('data-theme', value)
      } else {
        const key = mapKey[prop]
        this.handleStyle(key, value)
      }
    },
    // 赋值
    changeTagrgetAttr ({ str, key = 'color', value = 'green' }) {
      const REXFix = /(.+?)\{/
      const fixStr = str.match(REXFix)[1]
      const REX = /\{(.+?)\}/g
      const attrEle = str.match(REX)[0]
      const result = attrEle.match(/\{(.+?):/)
      return result[1] === key ? fixStr + attrEle.replace(/:(.*)/, `:${value} !important}`) : fixStr + attrEle
    },
    // .ka-siderBar{background-color:blue !important} => [.ka-siderBar{background-color:blue !important}]
    getInnerTextToArray ({ text, key, value }) {
      const REX = /(\[data-theme=custom])(.+?)\{(.+?)\}/g
      return this.arrayToString({ array: text.match(REX), key, value })
    },
    // .ka-siderBar{background-color:blue !important}=>.ka-siderBar{background-color:black !important}
    arrayToString ({ array, key, value }) {
      if (Array.isArray(array)) {
        return array.reduce((cur, next) => {
          cur += this.changeTagrgetAttr({ str: next, key, value })
          return cur
        }, '')
      }
      return ''
    },
    async handleStyle (key, value) {
      const themeTalk = document.getElementById('theme-talk')
      let styleContent = ''
      if (themeTalk) {
        styleContent = this.getInnerTextToArray({ text: themeTalk.innerText, key, value })
      } else {
        const head = document.getElementsByTagName('head')[0]
        const styles = [].slice.call(head.getElementsByTagName('style'))
        styles.forEach(v => {
          styleContent += this.getInnerTextToArray({ text: v.innerText, key, value })
        })
      }
      this.updateDomHeadStyle('theme-talk', styleContent)
    },
    async update ({ fontColor }) {
      // const head = document.getElementsByTagName('head')[0]
      // const styles = [].slice.call(head.getElementsByTagName('style'))
      // console.log(styles, 'styles')
      // styles.forEach((style, index) => {
      //   const { innerText } = style
      //   if (typeof innerText !== 'string') {
      //     return
      //   }
      //   style.innerText = this.handleStyle(innerText)
      // })
      // const data = await this.getCSSString('http://192.168.21.108:8081/css.scss')
      // const str = data.replace(/\$bgColor/g, fontColor)
      // const res = str.replace(/\n+/ig, '').replace(/\s*/g, '')
      // this.updateDomHeadStyle('updateStyle', res)
    },
    updateDomHeadStyle (id, styleContent) {
      let styleTag = document.getElementById(id)
      if (!styleTag) {
        styleTag = document.createElement('style')
        styleTag.setAttribute('id', id)
        document.head.appendChild(styleTag)
      }
      styleTag.innerText = styleContent.replace(/@font-face{[^}]+}/, '')
    },
    showThemeSetting () {
      this.$refs.baseDialog.show() // 弹窗显示
    }
  }
}
</script>

<style>

</style>
